#include <Def.h>
#include <qdebug.h>
#include "ModuleInfo.h"
#include "AddonPanel.h"
#include "addon/AddonManagerPrivate.h"
#include "SDKCore.h"
#include "util.h"

AddonPanel::AddonPanel(QWidget* parent):
WidgetFrameLess(parent)
{
	setFixedSize(240,480);
	appWidget = parent;

	auto ui = AddonManager::instance()->d_func()->getAddonPanel();
	layout()->addWidget((QWidget*)ui.treeWidget->parent());

	connect(ui.button,SIGNAL(clicked()),this,SLOT(onSearch()));
	//connect(ui.addonListButton,SIGNAL(clicked()),SLOT(onClickAddonList()));

	connect(ui.treeWidget,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(onClickAddonItem(QTreeWidgetItem*,int)));
}

AddonPanel::~AddonPanel()
{
}

void AddonPanel::onSearch()
{
}

void AddonPanel::onClickAddonItem(QTreeWidgetItem* item,int col)
{
	QString package = item->data(0,Qt::UserRole).toString();
	QString addonName = item->text(0);

	qDebug() << "AddonPanel onClick Item:" << package << "," << addonName;
	if(package.isEmpty() || addonName.isEmpty())
		return;

	QWidget* widget = nullptr;
	QString key = QString("%1--#--%2").arg(package).arg(addonName);
	if(widgetList.contains(key))
	{
		widget = widgetList[key];
		if (widget->isVisible())
			widget->hide();
		else
			widget->show();
		return;
	}

	auto packageObject = AddonManager::instance()->getPackageByName(package);
	if(!packageObject)
		return;

    auto addonObject = packageObject->getAddonByName(addonName);
	if(!addonObject)
		return;

	widget = addonObject->createAddonWidget(appWidget);
	//widget->setParent(appWidget);
	widgetList.insert(key,widget);
	widget->show();
}

